#pragma once
#include "common.h"
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>

#define AF_ERR -1
#define ALL_LIST_LEN 10//全连接队列长度

class network
{
public:
    //封装了socket、bind、listen
    static int TcpServer(int port)
    {
        int fd = CreateTcpSocket();
        
        if(Bind(fd,port) && Listen(fd,ALL_LIST_LEN))
          return fd;
        else
          return AF_ERR;
    }
    static int TcpAccept(int fd)
    {
        return accept(fd,nullptr,nullptr);
    }
    static int TcpConnect()
    {
   
    }
private:
    static int CreateTcpSocket()
    {
      int fd = socket(AF_INET,SOCK_STREAM,0);

      if(fd<0)
        return AF_ERR;
      else
        return fd;
    }
    static bool Bind(int fd,ushort port)
    {
          sockaddr_in sa;
          memset(&sa,0,sizeof(sa));
          sa.sin_family=AF_INET;
          sa.sin_port=htons(port);
          sa.sin_addr.s_addr = htonl(INADDR_ANY);
          int ret = bind(fd, (struct sockaddr*)&sa, sizeof(sa));
          if(ret<0)
          {
            return AF_ERR;
            close(fd);
          }
          else
          return true;
    }
    static bool Listen(int fd,int len)
    {
       int ret = listen(fd,len);
       if(ret==-1)
       {
        close(fd);
        return false;
       }
       else
       return true;
    }  
};